//
//  HMStatusViewModel.swift
//  WymanWeibo
//
//  Created by wyman on 16/4/13.
//  Copyright © 2016年 wyman. All rights reserved.
//

import UIKit
import SDWebImage
class HMStatusViewModel: NSObject {
    private var loadStatusing: Bool = false
    static let sharedInstance: HMStatusViewModel = HMStatusViewModel()
    
    //加载微博数据
       //请求数据
    func loadStatus(since_id: Int64, max_id: Int64, loadStatusCallback: (statuses: [HMStatus]?,error: NSError?) -> ()){
    
        if loadStatusing == true {
            // 有人在加载微博数据
            HMPrint("有人在加载微博数据")
            let error = HMNetworkErrorEnum.RepeatLoadStatus.error()
            loadStatusCallback(statuses: nil, error: error)
            return
        }
        
        // 将加载的状态改成ture,表示有人在加载微博
        loadStatusing = true
        let urlSting = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        //参数
        var parameters: [String: AnyObject] = ["access_token":HMUserAccountViewModel.shareInstance.userAccount!.access_token!]
        
        if since_id > 0 {
            parameters["since_id"] = NSNumber(longLong: since_id)
        }else if max_id > 0{
        
            parameters["max_id"] = NSNumber(longLong: max_id-1)

        }
        
//         parameters["count"] = 1
        
        HMNetworkTool.sharedInstanse.GET(urlSting, parameters: parameters, progress: nil
            , success: { (task, resObject) in
//                HMPrint("获取微博数据成功了: \(resObject)")
                 self.loadStatusing = false
                if let dict = resObject as? [String: AnyObject],let statusDict = dict["statuses"] as? [[String: AnyObject]]
                {
                //定义数字来保存数据
                    var statusModels: [HMStatus] = []
                    
                    for dict in statusDict{
                        let status = HMStatus(dict: dict)
                        
                        //模型添加到数组
                        statusModels.append(status)
                    
                    }
                   self .cacheWebImage(statusModels, loadStatusCallback: loadStatusCallback)
                    
                }
            }) { (task, error) in
                HMPrint("获取微博数据失败了: \(error)")
                loadStatusCallback(statuses: nil, error: error)

        }
    
    }
    private func cacheWebImage(status:[HMStatus],loadStatusCallback: (statuses: [HMStatus]?, error: NSError?)-> ()){
    //创建任务组
        let group = dispatch_group_create()
        
        var downURLs: [NSURL]?
        //判断每个模型,是否要下载
        for statu in status{
            
            var downURLs: [NSURL]?

        //判断原创cell是否优质
            if statu.storePicutreURLs == nil{
            downURLs = statu.retweeted_status?.storePicutreURLs
            }
           
            //遍历,如果第一张,就加载
            if let urls = downURLs {
                if urls.count == 1 {
                    
                    let url = urls.first!

                    //用WEBiMGE加载 进入调度组
                    
                    dispatch_group_enter(group)
                    
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (image, error, _, _, _) in
                        dispatch_group_leave(group)
                        
                        if error != nil {
                            HMPrint("下载图片失败: \(url)")
                            return
                        }
                        
//                        HMPrint("下载图片完成: \(url)")
                    })
                    
                }
            
            }
        
        
        }
        
        //进入调度组
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            HMPrint("SD下载所有图片完成")
            // SD下载所有图片完成,回调控制器,控制器会拿到数据,然后刷新界面
            loadStatusCallback(statuses: status, error: nil)
        }

    
    
    }
    
    
    //MARK - 发微博
    
    func sendSttus(text: String, sendStatusCallback: (error: NSError?) -> ()){
      guard let acess_token = HMUserAccountViewModel.shareInstance.userAccount?.access_token
        else{
        
            print("access_token为空")
        
            let error = HMNetworkErrorEnum.AccessTokenEmpty.error()
            sendStatusCallback(error: error)
            return
        }
        
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        //参数
        let parameters = [
            "access_token": acess_token,
            "status": text
        ]
        
        //发送请求
        HMNetworkTool.sharedInstanse.POST(urlString, parameters: parameters, progress: nil, success: { (_, responseObject) -> Void in
            
            //发布成功了
            sendStatusCallback(error: nil)
            
            }) { (_, error) -> Void in
                
            //发布失败了
            sendStatusCallback(error: error)
        }
    
    }
    
    
//    func text(){
    
        // 如果原创没有图片要下载,看被转发微博是不是有图片要下载
        //            if downloadURLs == nil {
        //                downloadURLs = status.retweeted_status?.storePicutreURLs
        ////                if downloadURLs == nil {
        ////                    return
        ////                }
        //            }
        
        // 看看是否有图片要下载
        
        //            for url in downloadURLs!{
        
        //                if let urls = downloadURLs {
        // 只有一张图片的时候才需要提前下载.多张图片的时候可以等到tableView显示出来的时候在去下载也可以,这样可以提高微博加载速速
        //                    if urls.count == 1 {
        // 获取一张要下载的图片的url地址
        //                        let url = urls.first!
        //                for url in urls {
        // 使用SDWebImage去下载图片
        // options: [SDWebImageOptions.AvoidAutoSetImage, SDWebImageOptions.CacheMemoryOnly]
        // 异步任务之前进入组
        //                        dispatch_group_enter(group)
        //                        // SDWebImage异步下载图片
        //                        SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in // 异步任务完成会回调这个闭包
        //                            dispatch_group_leave(group)
        //
        //                            if error != nil {
        //                                HMPrint("下载图片失败: \(url)")
        ////                                return
        //                            }
        //
        //                            HMPrint("下载图片完成: \(url)")
        //                        })
        //
        //                
        //            
        //            }
//    }
    
    
}
















